<template>
  <div ref="container"></div>
</template>

<script>
import * as d3 from 'd3';

export default {
  data() {
    return {
      values: [],
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      // 设置容器元素大小
      const container = this.$refs.container;
      const width = container.offsetWidth;
      const height = container.offsetHeight;

      // 初始化D3.js
      const svg = d3.select(container).append('svg').attr('width', width).attr('height', height);

      // 设置x轴比例尺
      const xScale = d3.scaleLinear().domain([0, 100]).range([width, 0]);

      // 设置y轴比例尺
      const yScale = d3.scaleLinear().domain([0, 100]).range([height, 0]);

      // 绘制x轴
      const xAxis = svg.append('g').attr('transform', `translate(0, ${height})`).call(d3.axisBottom(xScale));

      // 绘制y轴
      const yAxis = svg.append('g').call(d3.axisLeft(yScale));

      // 绘制折线路径
      const line = d3.line()
          .x((d, i) => xScale(i))
          .y((d) => yScale(d))
          .curve(d3.curveLinear);

      const path = svg.append('path')
          .datum(this.values)
          .attr('fill', 'none')
          .attr('stroke', 'steelblue')
          .attr('stroke-width', 2)
          .attr('d', line);

      // 更新数据
      setInterval(() => {
        this.values.unshift(Math.floor(Math.random() * 100));
        path.datum(this.values).attr('d', line);
      }, 1000); // 每一秒更新一次数据
    },
  },
};
</script>

<style scoped>
svg {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 2px;
}
</style>